package com.sky.youxue.controller;

import com.alibaba.fastjson.JSONObject;
import com.sky.youxue.service.UserService;
import com.sky.youxue.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping
public class UserController {

    @Autowired
    public UserService userService;

    /**
     * 用户注册的方法
     * @param code
     * @return
     */
//    @Valid
    @PostMapping("insertUser")
    public ResponseEntity<Void> userRegister(@RequestParam("code")String code, @RequestBody JSONObject param) {
        User user = param.toJavaObject(User.class);
        System.out.println(code+","+ user.getUsername()+","+user.getPassword()+","+user.getPhone()+","+user.getSalt());
        Boolean boo = this.userService.register(user,code);
        System.out.println(" 插入结果："+boo);
        if (boo == null || !boo) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 校验用户名和密码是否正确
     * @param username
     * @param password
     * @return
     */
    @GetMapping("queryUser")
    public ResponseEntity<User> queryUser(
            @RequestParam(value = "username",required = true)String username,
            @RequestParam(value = "password",required = true)String password
    ){
        System.out.println(username+" "+password);
        User user = this.userService.queryUserByIdAndPassword(username,password);
        if (user==null){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        System.out.println(user);
        return ResponseEntity.status(HttpStatus.OK).body(user);
    }

    @GetMapping("deleteUser")
    public ResponseEntity<Void> deleteUser(@Valid  User user){
        Boolean result = userService.deleteUser(user);
        if (result == null || !result) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }


    @PostMapping("updateUser")
    public ResponseEntity<Void> updateUser(@Valid User user){
        Boolean result = userService.updateUser(user);
        if (result == null || !result) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
}
